package com.lis.scf.security;


//import com.enterprise.service.JwtService;
//import com.enterprise.service.UserDetailsServiceImpl;
import com.lis.scf.service.JwtService;
import com.lis.scf.service.UserService;
import com.lis.scf.service.impl.UserDetailsServiceImpl;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT认证过滤器（每次请求执行一次）
 */
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtService jwtService;
    private final UserDetailsServiceImpl userDetailsService;
    private final UserService userService;



    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws ServletException, IOException {
        // 1. 从请求头获取Authorization
        final String authHeader = request.getHeader("Authorization");
        final String jwt;
        final String username;

        // 2. 检查Authorization格式（必须以Bearer开头）
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 3. 提取令牌（去掉"Bearer "前缀）
        jwt = authHeader.substring(7);
        try {
            // 4. 解析令牌获取用户名
            username = jwtService.extractUsername(jwt);

            System.out.println(username);

            // 5. 如果用户名存在且未认证
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

                // 6. 加载用户信息
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

                // 7. 验证令牌有效性
                if (jwtService.isTokenValid(jwt, String.valueOf(username))) {
                    // 8. 设置认证信息到上下文

                    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                            userDetails,
                            null,
                            userDetails.getAuthorities()
                    );

                    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authToken);
                }
            }
        } catch (Exception e) {
            // 令牌解析失败（过期、签名错误等），不设置认证信息
            logger.error("无法设置用户认证: {}");
        }

        // 9. 继续执行过滤器链
        filterChain.doFilter(request, response);
    }
}
